/*
 * @lc app=leetcode.cn id=2182 lang=cpp
 *
 * [2182] 构造限制重复的字符串
 */

// @lc code=start
class Solution
{
public:
    string repeatLimitedString(string s, int repeatLimit)
    {
        sort(s.begin(), s.end(), [](char a, char b)
             { return a > b; });

        string ans = "", temp;
        int i = 0, n = s.size();
        while (i < n)
        {
            temp = "";
            temp += s[i], i++;
            while (temp[0] == s[i])
            {
                temp += s[i], i++;
            }

            int j = 0;
            while (temp.size() - j > repeatLimit)
            {
                ans += temp.substr(j, repeatLimit);
                if (i >= n)
                    return ans;
                ans += s[i], i++;
                j += repeatLimit;
            }

            if (j < temp.size())
            {
                ans += temp.substr(j);
            }
        }

        return ans;
    }
};
// @lc code=end
